<template>
  <div style="height:100%">
    <div class="topNav">
      <div class="top_left">
        <span @click="listClick('list')" :class="listShow ? 'listClass' : ''">列表</span>
        <span @click="listClick('map')" style="margin-left: 16px;" :class="mapShow ? 'listClass' : ''">地图</span>
      </div>
      <span class="top_right">
        <img style="width: 11px; margin-right: 5px;" src="~@/assets/images/reglocation.png" alt="" />
        {{ city || '未获取到位置' }}
      </span>
    </div>
    <div class="content" v-show="listShow">
      <div class="contentList" v-for="cus in OutletsList" :key="cus.id">
        <div class="listContent">
          <div>
            <img style="float:left;width: 6%;padding-top: 3px;;" src="~@/assets/images/regAdd.png" alt="" />
            <div style="margin-left:9%;width: 88%">
              <div style="line-height: 24px;font-size: 16px;font-weight: bold;">{{ cus.fullname }}</div>
              <div style="line-height: 24px;margin-top: 5px;font-size:13px;color:#999">
                {{ cus.address }}
              </div>
            </div>
          </div>
          <div class="contentNav">
            <span @click="lineUPQuery(cus.id)" style="width:31%">
              <img class="navIcon" src="~@/assets/images/regpaidui.png" alt="" />
              排队查询 </span
            >|
            <span @click="toReserva(cus)">
              <img class="navIcon" src="~@/assets/images/regyuyue.png" alt="" />
              预约 </span
            >|
            <span @click="toQueuing(cus)">
              <img class="navIcon" src="~@/assets/images/regquhao.png" alt="" />
              取号 </span
            >|
            <span @click="toLocation(cus.wdLatitude, cus.wdLongitude)">
              <img class="navIcon" src="~@/assets/images/regdaohang.png" alt="" />
              导航
            </span>
          </div>
        </div>
        <div class="lineQuery" v-show="cus.lineShow">
          <div class="lineContent">
            <table style="width:100%;">
              <tr style="color:#4D4D4D">
                <th style="text-align: left">业务名称</th>
                <th>当前办理</th>
                <th style="text-align: right">等候</th>
              </tr>
              <tr v-for="fl in cus.queues" style="color:#999999" :key="fl.id">
                <td>{{ fl.serviceTypeName }}</td>
                <td style="text-align: center">{{ fl.countProcessing || '暂无' }}</td>
                <td style="text-align: right">
                  <span style="padding-right: 3px">{{ fl.countWaiting }}</span
                  >人
                </td>
              </tr>
            </table>

            <div style="line-height: 40px;padding: 3px 18px 0;color:#4D4D4D;font-size:13px">
              <span>该营业厅当前排队</span>
              <span style="float:right;"
                >共<span style="color:#FFAE00;margin: 0 3px">{{ cus.countQueue || 0 }}</span
                >人</span
              >
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="content mapcontent" v-show="mapShow">
      <div class="map" id="map"></div>
      <div class="mapsearch">
        <img class="img_icon" src="~@/assets/images/req_icon_search.png" alt="" />
        <input
          class="mapsearch_input"
          type="text"
          placeholder="搜索"
          v-model="searchfullname"
          @change="lineQueryList()"
        />
      </div>
      <div class="maplist">
        <div
          v-for="cus in OutletsList"
          :key="cus.id"
          :class="[cus.select ? 'select' : '', 'mapitem']"
          @click="locationMap(cus)"
        >
          <div class="mapitem_header">
            <div class="mapitem_header_name ellipsis">{{ cus.fullname }}</div>
            <div class="mapitem_header_distance">{{ cus.distance || 0 }}公里</div>
          </div>
          <div class="mapiteminfo address ellipsis">{{ cus.address }}</div>
          <div class="mapiteminfo time">{{ cus.wdWorkAmBegin}}-{{ cus.wdWorkAmEnd}} {{ cus.wdWorkPmBegin}}-{{ cus.wdWorkPmEnd}}</div>
          <a class="mapiteminfo tel" :href="'tel:' + cus.wdTel">{{ cus.wdTel }}</a>
          <div class="mapiteminfo queue">
            该网点当前排队<span class="peoplenum">{{ cus.wdCountnum || 0 }}</span
            >人
          </div>
          <ul class="item_button_group">
            <li class="item_btn" @click.prevent="toLocation(cus.wdLatitude, cus.wdLongitude)">网点导航</li>
            <li class="item_btn" @click.prevent="toReserva(cus)">前往预约</li>
            <li class="item_btn" @click.prevent="toQueuing(cus)">前往取号</li>
          </ul>
        </div>
      </div>
    </div>
  </div>
</template>
<script lang="ts">
import '../../style/reservaIndex_index.css';
import 'vant/lib/toast/style';
import 'vant/lib/dialog/style';
import { Component, Vue, Prop } from 'vue-property-decorator';
import { Toast, Dialog } from 'vant';
import { cloudApi } from '@/api/indexApi';
import Header from '@/components/Header.vue';
Vue.use(Toast);
Vue.use(Dialog);
Component.registerHooks(['beforeRouteUpdate', 'beforeRouteLeave', 'beforeRouteLeave']);
@Component({
  components: { Header },
})
export default class ReservaIndex extends Vue {
  listShow: boolean = true;
  mapShow: boolean = false;
  lineShow: boolean = false;
  OutletsList: Array<any> = [];
  lat: number = 39.908024;
  lng: number = 116.397915; //定位失败时默认天安门
  city: string = ''; //城市名称
  citycode: string = ''; //城市code
  openId: string = '';
  isoneload: boolean = false; //是不是第一次进入
  map: any = null;
  mypositionIcon: any = null; //当前定位的图标
  mypositionMark: any = null; // 当前定位的mark
  netpositionIcon: any = null; // 网点图标
  netpositionMark: any = null; //网点定位的mark
  selectNet: any = null; //选中的服务网点
  searchfullname: string = ''; //查询的服务网点名称
  longitude: any ='';
  latitude: any = '';
  created(){
    (document.querySelector('html') as any).style.height= '100%';
    var mysize = new (window as any).qq.maps.Size(16, 28);
    var myscaleSize = new (window as any).qq.maps.Size(16, 28);
    var size = new (window as any).qq.maps.Size(28.5, 38);
    var scaleSize = new (window as any).qq.maps.Size(28.5, 38);
    var myimg = require('../../assets/images/reqmylocation.png');
    var netimg = require('../../assets/images/reqnetlocation.png');
    var myicon = new (window as any).qq.maps.MarkerImage(myimg, mysize, null, null, myscaleSize);
    var neticon = new (window as any).qq.maps.MarkerImage(netimg, size, null, null, scaleSize);
    this.mypositionIcon = myicon;
    this.netpositionIcon = neticon;
    if(this.$route.query.type == 'map'){
      this.listShow = false;
      this.mapShow = true;
    }
    var openid = sessionStorage.getItem('openId');
    if(openid){
      this.openId = openid;
      this.isOneLoad();
    }
  }
  beforeDestroy(){
    (document.querySelector('html') as any).style.height= 'auto';
  }
  mounted() {
    this.getSigna();
  }
  listClick(type: any) {
    if (type == 'list') {
      this.listShow = true;
      this.mapShow = false;
    } else {
      this.listShow = false;
      this.mapShow = true;
    }
  }
  lineQueryList() {
    // Toast.loading({
    //   duration: 0,
    //   message: '加载中...',
    //   forbidClick: true,
    // });
    var _this = this;
    _this.OutletsList = [];
    cloudApi
      .QueryTheListOfOutlets({
        cityCode: _this.citycode,
        longitude: _this.lng,
        latitude: _this.lat,
        fullName: _this.searchfullname,
      })
      .then((res: any) => {
        // Toast.clear();
        if(res.data){
          if(res.data.code=='0000'){          
            if(res.data.OutletsList){
              // console.log(res.data.OutletsList)
              if(res.data.OutletsList.length == 0){
                Toast('暂无数据');
              }
              res.data.OutletsList.forEach(function(ele: any) {
                ele.address = ele.wdShengName + ele.wdShiName + ele.wdXianName + ele.wdAddress;
                ele.lineShow = false;
                ele.queues = [];
                ele.select = false;
              });
              _this.OutletsList = res.data.OutletsList;
            }
          }else{
            Dialog.confirm({
              title: '温馨提示',
              message: res.data.message,
              confirmButtonColor: '#009B63',
            })
            return;
          }
        }
      });
  }
  // 点击排队查询
  lineUPQuery(departId: any) {
    var _this = this;
    cloudApi
      .queryLineUp({
        departId: departId,
      })
      .then((res: any) => {
        if(res.data.code=='0000'){
        if (res.data.queuesData) {
          _this.OutletsList.forEach(function(ele: any) {
            ele.lineShow = false;
            if (ele.id == departId) {
              ele.lineShow = true;
              ele.countQueue = Number(res.data.countQueue);
              if (res.data.queuesData.queues && res.data.queuesData.queues.length > 0) {
                res.data.queuesData.queues.forEach((elem: any) => {
                  if(elem.serviceType == '01'){
                    elem.serviceTypeName = '承保';
                  } else if(elem.serviceType == '02'){
                    elem.serviceTypeName = '理赔';
                  }
                });
                if(res.data.queuesData.queues.length == 1){
                  res.data.queuesData.queues[0].serviceType = '01';
                  res.data.queuesData.queues[0].serviceTypeName = '承保';
                  res.data.queuesData.queues.push({
                    countProcessing: 0,
                    countWaiting: 0,
                    dealStatus: "",
                    serviceType: "02",
                    serviceTypeName:'理赔'
                  })
                }
                ele.queues = res.data.queuesData.queues;
              }
            }
          });
        }
      }else{
        Dialog.confirm({
          title: '温馨提示',
          message: res.data.message,
          confirmButtonColor: '#009B63',
        })
        return;  
      }
      });
  }
  toQueuing(item: any){
    if(item.reservFlag != 1){
      Dialog.alert({
        title: '温馨提示',
        message: '该网点预约暂未开放，敬请期待',
        confirmButtonColor: '#009B63',
      });
      return;
    } 
    var _this = this;
    if (this.isoneload) {
      Dialog.confirm({
        title: '温馨提示',
        message: '首次预约时需绑定身份证信息，绑定信息成功后，证件号不能进行修改',
      }).then(() => {
        _this.$router.push({
          path: 'checkPhoneInfo',
          query: {
            unionId: sessionStorage.getItem('unionId'),
            openId: sessionStorage.getItem('openId'),
            route: JSON.stringify({
              path: 'Queuing',
              query: {
                unionId: sessionStorage.getItem('unionId'),
                openId: sessionStorage.getItem('openId'),
                longitude: String(this.lng),
                latitude: String(this.lat),
                departId: String(item.id),
              },
            })
          },
        });
      });
    } else {
      _this.$router.push({
        path: 'Queuing',
        query: {
          unionId: sessionStorage.getItem('unionId'),
          openId: sessionStorage.getItem('openId'),
          longitude: String(this.lng),
          latitude: String(this.lat),
          departId: String(item.id),
        },
      });
    }
    }
  toReserva(item: any) {
    if(item.reservFlag != 1){
      Dialog.alert({
        title: '温馨提示',
        message: '该网点预约暂未开放，敬请期待',
        confirmButtonColor: '#009B63',
      });
      return;
    }
    var _this = this;
    if (this.isoneload) {
      Dialog.confirm({
        title: '温馨提示',
        message: '首次预约时需绑定身份证信息，绑定信息成功后，证件号不能进行修改',
      }).then(() => {
        _this.$router.push({
          path: 'checkPhoneInfo',
          query: {
            unionId: sessionStorage.getItem('unionId'),
            openId: sessionStorage.getItem('openId'),
            route: JSON.stringify({
              path: 'register',
              query: {
                departId: item.id,
                openId: this.openId,
                address: item.address,
                fullname: item.fullname,
                longitude: String(this.lng),
                latitude: String(this.lat),
              },
            })
          },
        });
      });
    } else {
      _this.$router.push({
        path: 'register',
        query: {
          departId: item.id,
          openId: this.openId,
          address: item.address,
          fullname: item.fullname,
          longitude: String(this.lng),
          latitude: String(this.lat),
        },
      });
    }
  }
  getSigna() {
    var _this = this;
    cloudApi
      .getSignature({
        url: location.href.split("#")[0],
      })
      .then((res: any) => {
        if (res.data) {
          (window as any).wx.config({
            debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
            appId: res.data.appId, // 必填，公众号的唯一标识
            timestamp: res.data.timestamp, // 必填，生成签名的时间戳
            nonceStr: res.data.nonceStr, // 必填，生成签名的随机串
            signature: res.data.signature, // 必填，签名
            jsApiList: ['openLocation','getLocation'], // 必填，需要使用的JS接口列表
          });
          (window as any).wx.ready(function(res: any) {
            (window as any).wx.getLocation({
              type: 'gcj02',
              success: function(res: any) {
                _this.lat = res.latitude; // 纬度，浮点数，范围为90 ~ -90
                _this.lng = res.longitude; // 经度，浮点数，范围为180 ~ -180。
                _this.getcity(_this.lat, _this.lng);
                _this.initMap(_this.lat, _this.lng);
              },
              fail: function(res: any) {
                //定位失败
                _this.getcity(_this.lat, _this.lng);
                _this.initMap(_this.lat, _this.lng);
              },
              cancel: function(res: any) {
                //用户拒绝定位
                _this.getcity(_this.lat, _this.lng);
                _this.initMap(_this.lat, _this.lng);
              },
            });
          });
          (window as any).wx.error(function(res: any) {
            _this.getcity(_this.lat, _this.lng);
            _this.initMap(_this.lat, _this.lng);
          });
        } else {
          _this.getcity(_this.lat, _this.lng);
          _this.initMap(_this.lat, _this.lng);
        }
      });
  }
  getcity(a: any, b: any) {
    var _this = this;
    if (a == undefined || a == null || a == '') {
      a = this.lat;
    }
    if (b == undefined || b == null || b == '') {
      b = this.lng;
    }
    cloudApi
      .geocoder({
        //解析城市
        location: a + ',' + b,
        key: 'YW4BZ-XMVKD-GER4C-PFA67-E57R3-4BBML',
        get_poi: 0,
        callbackParamName: "QQmap",
        output:'jsonp'
      })
      .then((res: any) => {
        _this.citycode = res.data.result.ad_info.adcode.substr(0, 4); //市级编码
        _this.city = res.data.result.address_component.city;
        _this.lineQueryList();
      });
  }
  //是否是第一次进入
  isOneLoad() {
    var _this = this;
    cloudApi
      .isOneLoad({
        openId: this.openId,
      })
      .then(function(res: any) {
        if (res.data && res.data.code == '9999') {
          //是第一次进入
          _this.isoneload = true;
        }
      });
  }
  initMap(lat: any, lng: any) {
    this.map = new (window as any).qq.maps.Map(document.getElementById('map'), {
      center: new (window as any).qq.maps.LatLng(lat, lng),
      zoom: 13,
      scrollwheel: false,
      disableDoubleClickZoom: false,
    });
    this.addMark(lat, lng, 'my');
  }
  // 导航
  toLocation(latitude: any, longitude: any) {
    var ua = window.navigator.userAgent.toLowerCase();
    if (ua.match(/MicroMessenger/i) == 'micromessenger') {
      //微信
      (window as any).wx.openLocation({
        latitude: Number(latitude) || 0,
        longitude: Number(longitude) || 0,
        scale: 13,
      });
    }
  }
  addMark(lat: any, lng: any, icon: any) {
    //添加定位标记
    var position = new (window as any).qq.maps.LatLng(lat, lng);
    this.map.panTo(new (window as any).qq.maps.LatLng(lat, lng));
    if (icon == 'my') {
      this.mypositionMark = new (window as any).qq.maps.Marker({
        icon: this.mypositionIcon,
        position: position,
        map: this.map,
      });
    } else {
      this.netpositionMark ? this.removeMark(this.netpositionMark) : null;
      this.netpositionMark = new (window as any).qq.maps.Marker({
        icon: this.netpositionIcon,
        position: position,
        map: this.map,
      });
    }
  }
  removeMark(mark: any) {
    mark.setMap(null);
  }
  locationMap(item: any) {
    let _this = this;
    this.selectNet = item.id;
    this.OutletsList.forEach(function(ele: any) {
      if (ele.id == _this.selectNet) {
        ele.select = true;
      } else {
        ele.select = false;
      }
    });
    this.addMark(item.wdLatitude, item.wdLongitude, 'net');
  }
}
</script>
<style lang="less" scoped>
.ellipsis{
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  width:75%;
}
</style>
